<?php

namespace app\admin\controller;

use app\admin\model\SmsRechargeLogModel;
use app\admin\model\SmssendLog as SmsSendLogModel;
use app\common\controller\Backend;
use think\Db;
use think\Exception;
use think\exception\PDOException;

/**
 * 账单
 *
 * @icon fa fa-circle-o
 */
class Bill extends Backend
{

    /**
     * Bill模型对象
     * @var \app\admin\model\Bill
     */
    protected $model = null;
    protected $searchFields = 'id,contract_id'; // 确保包含contract_id
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Bill;
        $this->view->assign("statusList", $this->model->getStatusList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        $contract_id = $this->request->get('contract_id');
        if ($this->request->isAjax()) {

            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            if($contract_id){
                $this->model->where('contract_id',$contract_id);
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(['user','usercontract'])
                ->where($where)
                //->where('user_id',$this->auth->id)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row) {

                $row->getRelation('user')->visible(['nickname']);
            }
            /*
             * $contract_data = Db::name("user_contract")->where(['id'=>$v['contract_id']])->find();
                $list->items()[$k]['zu_user_name'] = $contract_data['user_name'];
                $list->items()[$k]['zu_sex'] = $contract_data['sex'];
                $list->items()[$k]['zu_user_card'] = $contract_data['user_card'];
                $list->items()[$k]['zu_user_phone'] = $contract_data['user_phone'];
                $list->items()[$k]['build_address'] = $contract_data['build_address'];
                $list->items()[$k]['build_name'] = $contract_data['build_name'];
             */

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    public function del($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $list = $this->model->where('id', 'in', $ids)->select();

        $count = 0;
        Db::startTrans();
        try {
            foreach ($list as $item) {
                // 已收款不可删除
                if ($item->status == 2) continue;
                $item->data('del_uid', $this->auth->id);
                $count += $item->delete();
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error('删除失败');
    }

    public function sms()
    {
        $id = $this->request->param('ids');
        $row = $this->model::get($id);
        if (empty($row)) {
            $this->error('数据不存在');
        }
        $contract = \app\admin\model\user\Contract::get($row->contract_id);
        if (empty($contract)) {
            $this->error('关联合同不存在');
        }
        $rechargeLog = SmsRechargeLogModel::isCanSend($this->auth->id);
        if (!$rechargeLog) {
            $this->error('请先充值短信');
        }

        Db::startTrans();
        try {
            $mobile = $contract->user_phone;
            // 短信模板参数
            $param = [
                'address' => $contract->build_address . $contract->room_name,
                'money' => $row->money,
                'date' => $row->month . '-' . $contract->rent_day,
            ];


            SmsSendLogModel::create([
                'user_id' => $this->auth->id,
                'contract_id' => $row->contract_id,
                'bill_id' => $id,
                'mobile' => $mobile,
                'create_time'=>time(),
                'update_time'=>time(),
                'content' => sprintf('尊敬的用户您好，您租住的%s，房租%s元，交租日期%s，为避免给您的生活带来不便，请及时缴纳。',
                    $param['address'], $param['money'], $param['date'])
            ]);

            $rechargeLog->send_num += 1;
            $rechargeLog->save();

            $res = \app\common\library\Sms::notice($mobile, $param, 'SMS_492610192');
            if (!$res) {
                throw new Exception('短信发送失败，请检查短信配置');
            }

            Db::commit();
        } catch (\Throwable $e) {
            Db::rollback();
            trace('发布短信失败：' . $e->getTraceAsString());
            $this->error($e->getMessage());
        }
        $this->success('成功');
    }

    public function audit()
    {
        $ids = $this->request->param('ids');

        $list = $this->model->where('id', 'in', $ids)->select();

        $count = 0;
        Db::startTrans();
        try {
            foreach ($list as $item) {
                // 已收款不可再审核
                if ($item->status == 2) continue;
                $count += $item->save(['status' => 1]);
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success('审核成功');
        }
        $this->error('暂无待审核数据');
    }

    public function receive_payment()
    {
        $ids = $this->request->param('ids');

        $list = $this->model->where('id', 'in', $ids)->select();

        $count = 0;
        Db::startTrans();
        try {
            foreach ($list as $item) {
                // 不是待审核不处理
                if ($item->status != 1) continue;
                $count += $item->save(['status' => 2, 'pay_time' => date('Y-m-d H:i:s')]);
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success('收款成功');
        }
        $this->error('暂无待收款数据');
    }

    public function revoke()
    {
        $ids = $this->request->param('ids');

        $list = $this->model->where('id', 'in', $ids)->select();

        $count = 0;
        Db::startTrans();
        try {
            foreach ($list as $item) {
                // 不是已支付不处理
                if ($item->status != 2) continue;
                $count += $item->save(['status' => 1, 'pay_time' => null]);
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success('撤销成功');
        }
        $this->error('失败');

    }

}
